<template>
  <u-navbar auto-back :title="getTitle()" bgColor="#fff"></u-navbar>
  <view class="main">
    <view class="textBox">
      <u-textarea
        maxlength="300"
        :disabled="disabled"
        border="none"
        v-model="formData.content"
        placeholder="禁止发布虚假、违规、违反广告法(投资理财、信贷)等内容，如有违规，平台有权直接删除并封号处理"
        :count="true"
      ></u-textarea>
    </view>
    <view class="scBox">
      <template v-if="formData.fileList.length > 0">
        <view class="box closeBox" v-for="(item, index) in formData.fileList" :key="index">
          <image :src="item?.url" mode="" @click.stop="TanPreviewImage(formData.fileList, index)"></image>
          <view class="icon" @click="deleteFn(index)">
            <u-icon name="close"></u-icon>
          </view>
        </view>
      </template>
      <view v-if="formData.fileList.length < 9" class="box" @click="uploadImg">
        <u-icon name="plus" color="#C9CDD8" size="30"></u-icon>
      </view>
    </view>
    <view class="switchBox" v-if="istgStatus === '1'">
      <u-cell-group :border="false">
        <u-cell title="广场置顶">
          <template #value>
            <u-switch v-model="formData.buyToppingFlag" @change="tgTypeFn(formData.promotionTime)" activeColor="#1676fc" activeValue="1" inactiveValue="0"></u-switch>
          </template>
        </u-cell>
        <u-cell :border="false" title="首页推广">
          <template #value>
            <u-switch v-model="formData.buyPromotionFlag" @change="tgTypeFn(formData.promotionTime)" activeColor="#1676fc" activeValue="1" inactiveValue="0"></u-switch>
          </template>
        </u-cell>
      </u-cell-group>
    </view>
    <view class="switchBox">
      <u-cell-group :border="false">
        <u-cell title="推广时长" v-if="formData.buyToppingFlag === '1' || formData.buyPromotionFlag === '1'">
          <template #value>
            <view class="sjBox">
              <view @click="tgTypeFn('3')" :class="{ item: true, active: formData.promotionTime === '3' }">3天</view>
              <view @click="tgTypeFn('7')" :class="{ item: true, active: formData.promotionTime === '7' }">7天</view>
              <view @click="tgTypeFn('30')" :class="{ item: true, active: formData.promotionTime === '30' }">30天</view>
            </view>
          </template>
        </u-cell>
        <u-cell title="有效期" is-link :value="formData.validDate" @click="goYXQPage"> </u-cell>
      </u-cell-group>
    </view>
    <view class="inputBox">
      <view class="title">推广行业</view>
      <view class="hyTetx" @click="goHYPage">
        <text>
          {{ getIndustryValue() }}
        </text>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>
    <u-datetime-picker :show="dateShow" mode="date" v-model="defaultDate" closeOnClickOverlay @confirm="dateComfirm" @cancel="dateShow = false" @close="dateShow = false"></u-datetime-picker>
    <view class="buttomBox">
      <view class="price" v-if="totalPrice !== 0">
        合计：<text class="unit">￥</text><text class="num">{{ totalPrice }}</text>
      </view>
      <view class="btn" :style="{ width: totalPrice === 0 ? '100%' : 'none' }" @click="submit">立即发布</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { BASE_UPLOADURL } from "@/utils/request";
import { goPage, TanPreviewImage } from "@/utils/commonFn";
import { getUserPostInfo, promotion, publishUserPost } from "@/api/order";
const { pageType, id } = defineProps<{
  pageType: string;
  id: string;
}>();
//@ts-ignore
import { onShow } from "@dcloudio/uni-app";
import { usePostStore } from "@/stores/post";
import dayjs from "dayjs";
import { configKey } from "@/api/my";
const getTitle = () => {
  if (pageType === "1") {
    return "我要供应";
  } else if (pageType === "2") {
    return "我要求购";
  } else {
    return "添加";
  }
};
const disabled = ref(false);
const istgStatus = ref("1");
const defaultDate = ref(new Date());
onMounted(async () => {
  const res1 = await configKey("promotion_switch");
  istgStatus.value = res1.data;
  if (id) {
    const res = await getUserPostInfo({ id });
    let arr: any = [];
    res.data.fileList.forEach((item) => {
      let obj = { url: item };
      arr.push(obj);
    });
    res.data.fileList = arr;
    formData.value = res.data;
    formData.value.buyToppingFlag = res.data.toppingFlag;
    formData.value.buyPromotionFlag = res.data.promotionFlag;
    disabled.value = true;
  }
});
const dateShow = ref(false);
onShow(() => {
  formData.value.industryList = usePostStore().selectIndustry as any;
});
const getIndustryValue = () => {
  if (formData.value.industryList.length > 0) {
    return formData.value.industryList.map((item: any) => item.industryName).join("、");
  } else {
    return "请选择";
  }
};
const formData = ref<any>({
  type: pageType,
  content: "",
  buyToppingFlag: "0",
  buyPromotionFlag: "0",
  promotionTime: "",
  validDate: "",
  industryList: [],
  fileList: [],
});
const deleteFn = (index: number) => {
  if (disabled.value) {
    return;
  }
  formData.value.fileList.splice(index, 1);
};
const totalPrice = ref(0);
const goHYPage = () => {
  if (disabled.value) {
    return;
  }
  goPage("/pages/myPage/myIndustry?otherPage=1");
};
const goYXQPage = () => {
  if (disabled.value) {
    return;
  }
  dateShow.value = true;
};
const tgTypeFn = async (type: string) => {
  formData.value.promotionTime = type;
  let price = 0;
  if (formData.value.buyToppingFlag === "1" && type === "3") {
    const res = await configKey("topping_price_3");
    price += +res.data;
  }
  if (formData.value.buyToppingFlag === "1" && type === "7") {
    const res = await configKey("topping_price_7");
    price += +res.data;
  }
  if (formData.value.buyToppingFlag === "1" && type === "30") {
    const res = await configKey("topping_price_30");
    price += +res.data;
  }
  if (formData.value.buyPromotionFlag === "1" && type === "3") {
    const res = await configKey("promotion_price_3");
    price += +res.data;
  }
  if (formData.value.buyPromotionFlag === "1" && type === "7") {
    const res = await configKey("promotion_price_7");
    price += +res.data;
  }
  if (formData.value.buyPromotionFlag === "1" && type === "30") {
    const res = await configKey("promotion_price_30");
    price += +res.data;
  }
  totalPrice.value = price;
};
const uploadImg = () => {
  if (disabled.value) {
    return;
  }
  uni.chooseImage({
    count: 9, //默认9
    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera"], //从相册选择或者打开相机
    success: function (res) {
      let tempFilePaths = res.tempFilePaths;
      for (let i = 0, len = tempFilePaths.length; i < len; i++) {
        uni.uploadFile({
          url: BASE_UPLOADURL, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[i],
          name: "file",
          header: {
            Authorization: uni.getStorageSync("token"),
          },
          success: (uploadFileRes) => {
            console.log(uploadFileRes, "uploadFileRes");
            //@ts-ignore
            formData.value.fileList.push({ url: JSON.parse(uploadFileRes.data).data });
            console.log(formData.value.fileList);
          },
        });
      }
    },
  });
};
const dateComfirm = (e: any) => {
  formData.value.validDate = dayjs(e.value).format("YYYY-MM-DD");
  dateShow.value = false;
};
const submit = async () => {
  let errorText = "";
  if (!formData.value.content) {
    errorText = "请填写内容";
  } else if (!formData.value.fileList) {
    errorText = "请选择图片";
  } else if (!formData.value.industryList) {
    errorText = "请选择行业";
  } else if (!formData.value.validDate) {
    errorText = "请选择有效期";
  }
  if (errorText) {
    uni.showToast({ icon: "none", title: errorText });
    return;
  }
  let res;
  if (id) {
    res = await promotion(formData.value);
  } else {
    res = await publishUserPost(formData.value);
  }

  if (res.data?.nonceStr) {
    let orderInfo: any = res.data;
    uni.requestPayment({
      provider: "wxpay",
      orderInfo,
      ...orderInfo,
      success(res: any) {
        if (res.errMsg == "requestPayment:ok") {
          uni.showToast({
            title: "购买成功",
            icon: "success",
            complete: () => {
              uni.showToast({
                title: "提交成功",
              });
              // 新的评论通知
              // 作品点赞提醒
              uni.requestSubscribeMessage({
                tmplIds: ["OgQrcRQNcRxP74d0tBenhZI2u-73A5wo4mJktFb4mHQ", "gjMI_lbJ6rdL0adg4JajB-G9mjW87eTRBRk9skl-dyw"],
                success() {},
                complete() {
                  setTimeout(() => {
                    usePostStore().setSelectIndustry([]);
                    uni.navigateBack();
                  }, 500);
                },
              });
            },
          });
        }
      },
      fail() {
        uni.showToast({
          title: "购买失败",
          icon: "error",
        });
      },
    });
  } else {
    uni.showToast({
      title: "提交成功",
    });
    // 新的评论通知
    // 作品点赞提醒
    uni.requestSubscribeMessage({
      tmplIds: ["OgQrcRQNcRxP74d0tBenhZI2u-73A5wo4mJktFb4mHQ", "gjMI_lbJ6rdL0adg4JajB-G9mjW87eTRBRk9skl-dyw"],
      success() {},
      complete() {
        setTimeout(() => {
          usePostStore().setSelectIndustry([]);
          uni.navigateBack();
        }, 500);
      },
    });
  }
};
</script>

<style lang="less" scoped>
.main {
  margin-top: 140rpx;
  padding-bottom: 130rpx;
}
.textBox {
  margin-top: 20rpx;
  border-radius: 18rpx;
}
.scBox {
  display: flex;
  flex-wrap: wrap;
  background: #fff;
  margin-top: 20rpx;
  padding: 32rpx;
  border-radius: 18rpx;
  .box {
    width: 140rpx;
    height: 140rpx;
    border-radius: 8rpx;
    background: #f5f8fc;
    margin-right: 16rpx;
    margin-bottom: 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    image {
      width: 140rpx;
      height: 140rpx;
    }
  }
}
.inputBox {
  background: #ffffff;
  margin-top: 20rpx;
  padding: 32rpx;
  border-radius: 18rpx;
  .title {
    font-size: 28rpx;
    color: #1e1e1e;
    line-height: 48rpx;
    margin-bottom: 24rpx;
  }
}
.switchBox {
  background: #ffffff;
  border-radius: 18rpx;
  padding: 0 20rpx;
  margin-top: 20rpx;
}
/deep/ .u-cell__body {
  padding: 20rpx 0rpx !important;
}
/deep/ .u-line {
  border-color: #f7f7f7 !important;
}
.sjBox {
  display: flex;
  align-items: center;
  .item {
    background: #f7f7f7;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #1e1e1e;
    line-height: 46rpx;
    padding: 3rpx 38rpx;
    margin-right: 10rpx;
  }
  .active {
    background: #1676fd;
    color: #fff;
  }
}
.buttomBox {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .price {
    font-size: 26rpx;
    font-family: DINPro, DINPro;
    font-weight: 400;
    color: #333333;
    line-height: 34rpx;
    margin-bottom: 10rpx;
    .unit {
      color: #fe5100;
    }
    .num {
      color: #fe5100;
      font-size: 40rpx;
    }
  }
  .btn {
    background: #1676fd;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 500;
    color: #ffffff;
    padding: 18rpx 30rpx;
    margin-left: 20rpx;
    transition: all 0.4s;
  }
}
.hyTetx {
  font-size: 28rpx;
  color: #606266;
  display: flex;
  justify-content: space-between;
}
</style>
